//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.wsd.smartcarwasher.controller;

import cn.hutool.core.util.RandomUtil;
import com.wsd.smartcarwasher.annotation.Log;
import com.wsd.smartcarwasher.constans.ResultState;
import com.wsd.smartcarwasher.domain.Admin;
import com.wsd.smartcarwasher.domain.UserInfo;
import com.wsd.smartcarwasher.service.*;
import com.wsd.smartcarwasher.util.RandomValidateCodeUtil;
import com.wsd.smartcarwasher.util.ReturnUtil;
import com.wsd.smartcarwasher.util.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Api(
        tags = {"登陆相关接口"}
)
@Controller
@CrossOrigin
public class UserLoginController {
    @Resource
    private UserInfoService userInfoService;
    @Resource
    private WxService wxService;
    @Resource
    private AdminService adminService;
    @Resource
    private PartnerService partnerService;
    @Resource
    private RedisService redisService;
    @Resource
    private HttpServletRequest request;
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    public UserLoginController() {
    }

    @GetMapping("/v1/newUser")
    public String newUser(@RequestParam(value = "userId") String userId,@RequestParam(value = "mobile") String mobile)
    {
        this.wxService.tellMachineNewUserRegistion(userId,mobile);
        return "成功";
    }

    @Log("管理端登陆")
    @ApiOperation(
            value = "管理端登陆",
            notes = "用户登陆",
            produces = "application/json",
            response = ModelMap.class
    )
    @ApiImplicitParam(
            name = "admin",
            value = "管理员信息",
            required = true,
            dataType = "Admin"
    )
    @RequestMapping(
            value = {"/v1/login_by_password"},
            method = {RequestMethod.POST},
            produces = {"application/json; charset=utf-8"}
    )
    @ResponseBody
    public ModelMap loginByMobile(@RequestBody Map<String, String> params, HttpServletRequest request) {
        String randomStr = (String)params.get("randomStr");
        String verify = (String)params.get("verify");
        String random = (String)this.redisService.get(randomStr);
        if (StringUtils.isBlank(random)) {
            return ReturnUtil.Error("验证码已过期");
        } else if (StringUtils.isBlank(verify)) {
            return ReturnUtil.Error("请输入验证码");
        } else if (random.equals(verify)) {
            this.redisService.remove(randomStr);
            String cellphone = (String)params.get("username");
            if (StringUtil.isEmpty(cellphone)) {
                return ReturnUtil.Error(ResultState.USERNAME_IS_NULL.getMsg());
            } else {
                String password = (String)params.get("password");
                return StringUtil.isEmpty(password) ? ReturnUtil.Error(ResultState.PASSWORD_IS_NULL.getMsg()) : this.adminService.loginByPassword(cellphone, password);
            }
        } else {
            return ReturnUtil.Error("请输入正确的验证码");
        }
    }


    @ApiOperation(
            value = "商家端登陆",
            notes = "用户登陆",
            produces = "application/json",
            response = ModelMap.class
    )
    @ApiImplicitParam(
            name = "partner",
            value = "加盟商信息",
            required = true,
            dataType = "Partner"
    )
    @RequestMapping(
            value = {"/v1/store/login_by_password"},
            method = {RequestMethod.POST},
            produces = {"application/json; charset=utf-8"}
    )
    @ResponseBody
    public ModelMap storeLoginByMobile(@RequestBody Map<String, String> params, HttpServletRequest request) {
        String randomStr = (String)params.get("randomStr");
        String verify = (String)params.get("verify");
        String random = (String)this.redisService.get(randomStr);
        String name=(String)params.get("name");
        if (StringUtils.isBlank(random)) {
            return ReturnUtil.Error("验证码已过期");
        } else if (StringUtils.isBlank(verify)) {
            return ReturnUtil.Error("请输入验证码");
        } else if (random.equals(verify)) {
            this.redisService.remove(randomStr);
            String cellphone = (String)params.get("username");
            if (StringUtil.isEmpty(cellphone)) {
                return ReturnUtil.Error(ResultState.USERNAME_IS_NULL.getMsg());
            } if (StringUtil.isEmpty(name)) {
                return ReturnUtil.Error(ResultState.NAME_IS_NULL.getMsg());
            }
            else {
                String password = (String)params.get("password");
                return StringUtil.isEmpty(password) ? ReturnUtil.Error(ResultState.PASSWORD_IS_NULL.getMsg()):this.partnerService.loginByPassword(name,cellphone, password,request);
            }
        } else {
            return ReturnUtil.Error("请输入正确的验证码");
        }
    }

    @ApiOperation(
            value = "小程序登陆",
            notes = "用户登陆",
            produces = "application/json",
            response = ModelMap.class
    )
    @ApiImplicitParam(
            name = "code",
            value = "小程序码",
            required = true,
            dataType = "String"
    )
    @RequestMapping(
            value = {"/v1/login_by_weixin"},
            method = {RequestMethod.GET},
            produces = {"application/json; charset=utf-8"}
    )
    @ResponseBody
    public ModelMap loginByWeiXin(@RequestParam("code") String code) {
        return StringUtil.isEmpty(code) ? ReturnUtil.Error(ResultState.WX_CALLBACK_CODE_IS_NULL.getMsg()) : this.wxService.loginByWeiXin(code);
    }



    @RequestMapping(
            value = {"/v1/generateToken"},
            method = {RequestMethod.GET},
            produces = {"application/json; charset=utf-8"}
    )
    @ResponseBody
    public ModelMap generateToken(@RequestParam("code") String openId) {

        String sessionId = StringUtil.getRandomUUID("3rdSessionKey_");
        String sessionKey= RandomUtil.randomString(12);
        this.redisService.put(sessionId, openId + "---" + sessionKey, 7200L);
        UserInfo user = this.userInfoService.findByOpenId(openId);

        return ReturnUtil.Success(sessionId);
    }




    @ApiOperation(
            value = "用户权限校验",
            notes = "用户权限校验",
            produces = "application/json",
            response = ModelMap.class
    )
    @RequiresRoles(
            value = {"admin"},
            logical = Logical.AND
    )
    @RequestMapping(
            value = {"/v1/login_check"},
            method = {RequestMethod.GET},
            produces = {"application/json; charset=utf-8"}
    )
    @ResponseBody
    public ModelMap isLogin() {
        return ReturnUtil.Success("");
    }

    @ApiOperation(
            value = "退出登陆",
            notes = "退出登陆",
            produces = "application/json",
            response = ModelMap.class
    )
    @RequestMapping(
            value = {"/v1/loginOut"},
            method = {RequestMethod.GET},
            produces = {"application/json; charset=utf-8"}
    )
    @ResponseBody
    public ModelMap loginOut() {
        SecurityUtils.getSubject().logout();
        return ReturnUtil.Success("退出成功");
    }

    @ApiOperation(
            value = "获取验证码",
            notes = "获取验证码",
            produces = "application/json",
            response = ModelMap.class
    )
    @GetMapping({"/v1/getVerify"})
    public void getVerify(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setContentType("image/jpeg");
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expire", 0L);
            RandomValidateCodeUtil randomValidateCode = new RandomValidateCodeUtil();
            randomValidateCode.getRandcode(request, response, this.redisService);
        } catch (Exception var4) {
            this.logger.error("获取验证码失败>>>> ", var4);
        }

    }

    @Log("修改密码")
    @ApiOperation(
            value = "pc-修改用户密码",
            notes = "pc-修改用户密码",
            produces = "application/json",
            response = ModelMap.class
    )
    @RequestMapping(
            value = {"/v1/updatePassword"},
            method = {RequestMethod.POST},
            produces = {"application/json; charset=utf-8"}
    )
    @ResponseBody
    public ModelMap updatePasswod(@RequestBody Map<String, Object> filterCondition) {
        String newPassword = filterCondition.get("newPassword").toString();
        String password = filterCondition.get("password").toString();
        Integer id = Integer.valueOf(filterCondition.get("id").toString());
        if (StringUtils.isBlank(newPassword)) {
            return ReturnUtil.Error("新密码无效字符");
        } else if (password.equals(newPassword)) {
            return ReturnUtil.Error("新密码与旧密码不能相同");
        } else {
            Admin admin = this.adminService.getAdminById(id);
            String passwordMd5 = (new SimpleHash("MD5", password, admin.getSalt(), 2)).toString();
            if (!admin.getPassword().equals(passwordMd5)) {
                return ReturnUtil.Error("旧密码不正确");
            } else {
                admin.setPassword((new SimpleHash("MD5", newPassword, admin.getSalt(), 2)).toString());
                int rows = this.adminService.updatePassword(admin);
                return rows > 0 ? ReturnUtil.Success("修改成功！") : ReturnUtil.Error("修改失败");
            }
        }
    }


    public static void main(String[] args) {
        System.out.println((new SimpleHash("MD5", "123456", "1614213971119", 2)).toString());
    }


    @ApiOperation(
            value = "pc-个人信息",
            notes = "pc-个人信息",
            produces = "application/json",
            response = ModelMap.class
    )
    @RequestMapping(
            value = {"/v1/getAdminInfo"},
            method = {RequestMethod.POST},
            produces = {"application/json; charset=utf-8"}
    )
    @ResponseBody
    public ModelMap getAdminInfo() {
        Admin admin = (Admin)SecurityUtils.getSubject().getPrincipal();
        return admin == null ? ReturnUtil.Error("没有登陆") : ReturnUtil.Success("成功", admin);
    }
}
